package cn.itsource.mq;

import cn.itsource.pojo.bo.PayOrderBo;
import cn.itsource.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 📖：beishan
 * 🗓️：2024/4/19 18:11
 * =====================
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "consumer-pay",
        topic = "topic-payorder",
        selectorExpression = "tags-payorder"
)
public class PayConsumerListener implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService orderService;
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        //这里拿到的消息 message.getBody 是byte[]格式。
        if(body == null ||body.length == 0)return;
        String bodyStr = new String(body, StandardCharsets.UTF_8);
        PayOrderBo payOrderBo = JSON.parseObject(bodyStr, PayOrderBo.class);

        try {
            orderService.addPayOrder(payOrderBo);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return;
            }

        }

    }
}
